package com.javatom.notes.authority;

import com.javatom.notes.common.enums.HttpReponseCodeEnum;
import com.javatom.notes.common.model.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.*;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;

import org.springframework.stereotype.Component;

/**
 * @description: 自定义异常返回
 * @author: 曾维录
 * @time: 2019/7/31 18:02
 */
@Component(value = "webResponseExceptionTranslator")
@Slf4j
public class WebResponseExceptionTranslatorHandle extends DefaultWebResponseExceptionTranslator {
    public static final String BAD_MSG = "坏的凭证";

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        log.error("{}", e);

        R responseJson = R.fail(HttpReponseCodeEnum.FAILED);
        if(e instanceof UnsupportedGrantTypeException) {
            //不支持验证类型
            responseJson.setMsg("grant_type 不合法，不支持此类型");
        }else if (e instanceof InvalidGrantException) {
            responseJson.setMsg("密码错误");
        }else if (e instanceof InvalidScopeException){
            responseJson.setMsg("scope 错误");
        }else if (e instanceof UsernameNotFoundException){
            responseJson.setMsg(e.getMessage());
        }



        ResponseEntity response =  ResponseEntity.ok().body(responseJson);

        return response;
    }
}
